package com.yl.utils;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class WeiXinUtil {

    public static Map<String, String>  getJsSdk(String url,String wxgzAppID,String wxgzAppSecret) {
        Map<String, String> returnMap = new HashMap<String,String>();
        try {
            String ticket = getJsapiTicket(wxgzAppID,wxgzAppSecret);
            if(StringUtils.isNotBlank(ticket) && StringUtils.isNotBlank(url)){
                returnMap = sign(ticket, url);
                returnMap.put("appId", wxgzAppID);//微信公众号appId
            }
        } catch (Exception e) {
        }
        return returnMap;
    }

    public static Map<String, String>  getSdkByJs(String url,String wxgzAppID,String ticket) {
        Map<String, String> returnMap = new HashMap<String,String>();
        try {
            if(StringUtils.isNotBlank(ticket) && StringUtils.isNotBlank(url)){
                returnMap = sign(ticket, url);
                returnMap.put("appId", wxgzAppID);//微信公众号appId
            }
        } catch (Exception e) {
        }
        return returnMap;
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> result = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string;
        String signature = "";
        // 注意这里参数名必须全部小写，且必须有序
        string = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        result.put("url", url);
        result.put("jsapi_ticket", jsapi_ticket);
        result.put("nonceStr", nonce_str);
        result.put("timestamp", timestamp);
        result.put("signature", signature);
        return result;
    }

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }
    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    //注意：ticket有时间刷新限制
    public static String getJsapiTicket(String wxgzAppID,String wxgzAppSecret) throws Exception {
        String ticken = null;
        try {
            String access_token = getToken(wxgzAppID,wxgzAppSecret);
            System.out.println("#### access_token = " + access_token);
            if(access_token != null && StringUtils.isNotBlank(access_token)){
                // 创建HttpClient实例
                HttpClient httpclient = new DefaultHttpClient();
                // 创建Get方法实例
                HttpGet httpgets = new HttpGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi"); // 免费api
                HttpResponse response = httpclient.execute(httpgets);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instreams = entity.getContent();
                    String str = convertStreamToString(instreams);
                    JSONObject jsOb = JSONObject.fromObject(str);
                    httpgets.abort();
                    ticken = String.valueOf(jsOb.get("ticket"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticken;
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String getToken(String wxgzAppID,String wxgzAppSecret) throws Exception {
        String access_token = null;
        // 创建HttpClient实例
        HttpClient httpclient = new DefaultHttpClient();
        // 创建Get方法实例需要微信公众号appId+secret
        HttpGet httpgets = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wxgzAppID + "&secret=" + wxgzAppSecret);
        HttpResponse response = httpclient.execute(httpgets);
        HttpEntity entity = response.getEntity();
        Map<String, Object> maData = new HashMap<String, Object>();
        if (entity != null) {
            InputStream instreams = entity.getContent();
            String str = convertStreamToString(instreams);
            JSONObject jsOb = JSONObject.fromObject(str);
            httpgets.abort();
            access_token = String.valueOf(jsOb.get("access_token")).replaceAll("null","");
        }
        return access_token;
    }

}
